﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Website;
using FRLUser = FRL.DebtChased.Repository.User;
using FRLUserAccess = FRL.DebtChased.Repository.UserAccess;

namespace WebApplication
{

	/// <summary>
	/// Declaration of UserAccess class
	/// </summary>
	public partial class UserAccess : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

			}
			else
			{

				// Set colours
				pnlHeading.BackColor = MyApplication.BindMyApplication().PrimaryWebColor;
				pnlFooter.BackColor = pnlHeading.BackColor;

			}

		}

		protected void butLogon_Click(object sender, EventArgs e)
		{

			// Validate the page
			this.Page.Validate();
			if (!this.Page.IsValid)
				return;

			// Get address of request
			string strAddress;
			if(string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
				strAddress = Request.ServerVariables["REMOTE_ADDR"];
			else
				strAddress = string.Format("{0} via {1}",
					Request.ServerVariables["REMOTE_ADDR"],
					Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
				);

			// Contact the repository
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Check users credentials
				if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text))
				{

					// Load the user
					FRLUser user = FRLUser.GetUserByUsername(ent, txtUsername.Text);

					// Get my application
					MyApplication myApplication = MyApplication.BindMyApplication();

					// Create a session
					MySession mySession = MySession.BindMySession();
					mySession.LogOn(ent,user);
					mySession.SetTimeout(myApplication.SessionTimeoutMins);

					// Record the logging in
					FRLUserAccess.UserLoggedOn(ent, user, strAddress);

					// Create the cookie and add to response
					HttpCookie authCookie = FormsAuthentication.GetAuthCookie(txtUsername.Text, false);
					Response.Cookies.Add(authCookie);

					// Pick a page to redirect to
					string strHomePage = "~/Default.aspx";
                    if (user.Contains(Definitions.AnyFinUserRole))
                    {
                        //Tony Change
                        strHomePage = "~/Finance/DebtChaser.aspx";
                        //strHomePage = "~/Finance/Dashboard.aspx";
                    }
                    else if (user.Contains(Definitions.AnyClientUserRole))
                        strHomePage = "~/Client/Home.aspx";
                    else if (user.Contains(Definitions.eRoles.DEBTOR))
                        strHomePage = "~/Debtor/Home.aspx";
					Response.Redirect(strHomePage);

				}
				else
				{

					// Record the failed attempt to log in
					FRLUserAccess.FailedAuthentication(ent, strAddress, txtUsername.Text, txtPassword.Text);

					// Set error
					ltErrorMsg.Text = "The username and password combination were not recognised.";
					pnlError.Visible = true;

				}

			}

		}

		protected void butDebtorLogon_Click(object sender, EventArgs e)
		{

			// Validate the page
			this.Page.Validate();
			if (!this.Page.IsValid)
				return;

		}

		protected void lnkShortcut_Click(object sender, EventArgs e)
		{
#if DEBUG
			DebugLogin("rsalmon", "sunshine");
#endif // #if DEBUG
		}

		protected void lnkShortcut2_Click(object sender, EventArgs e)
		{
#if DEBUG
			DebugLogin("bmcgee", "sunshine");
#endif // #if DEBUG
		}

		/////////////////////////////////////////////////////////////
		// Operations

#if DEBUG
		public void DebugLogin( string strUsername, string strPassword )
		{
			txtUsername.Text = strUsername;
			txtPassword.Text = strPassword;
			butLogon_Click(null, null);
		}
#endif // #if DEBUG

	}

}